﻿//-----------------------------------------------------------------------------------------------------------
// WBFSSync Project by Omega Frost 
// http://wbfssync.codeplex.com/
//
// WBFSSync is Licensed under the terms of the 
// Microsoft Reciprocal License (Ms-RL)
//-----------------------------------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Threading;
using WbfsSync.Core.Operations;

namespace WbfsSync.Core
{
    //-------------------------------------------------------------------------------------------------------
    //
    //-------------------------------------------------------------------------------------------------------
    public static class Threads
    {
        //---------------------------------------------------------------------------------------------------
        //
        //---------------------------------------------------------------------------------------------------
        static ReaderWriterLock Lock = new ReaderWriterLock();
        static List<Operation> Operations = new List<Operation>();


        //---------------------------------------------------------------------------------------------------
        //
        //---------------------------------------------------------------------------------------------------
        public static void LaunchOperation(Operation operation, ParameterizedThreadStart routine)
        {
            operation.Thread = new Thread(routine);
            operation.Thread.Name = operation.Name;
            operation.Thread.Start(operation);

            operation.Completed += new OperationDelegate(operation_Completed);

            Lock.AcquireWriterLock(-1);
            Operations.Add(operation);
            Lock.ReleaseLock();
        }


        //---------------------------------------------------------------------------------------------------
        //
        //---------------------------------------------------------------------------------------------------
        static void operation_Completed(Operation sender, WBFSe3.WbfsError error, int element)
        {
            Lock.AcquireWriterLock(-1);
            Operations.Remove(sender);
            Lock.ReleaseLock();
        }
    }
}
